import axios from "axios";
import { message } from "antd";

export const baseURL = "http://localhost:3005";

const instance = axios.create({
    baseURL,
    timeout: 50000
});

instance.interceptors.request.use(config => {
    let token = localStorage.getItem('token');
    if(token) {
        config.headers.Authorization = `Bearer ${token}`;
    }

    return config;
}, error => Promise.reject(error));

instance.interceptors.response.use(resp => {
    // 实现单token的无限刷新的逻辑
    const newToken = resp.headers['token'];
    if(newToken) localStorage.setItem('token', newToken);

    return resp.data;
}, error => {
    if(!error.response) return Promise.reject(error.response);

    let { data } = error.response;
    if(data.statusCode === 401) {
        message.error(data.message);
        setTimeout(()=>{
            window.location.href = '/login';
        }, 1500);
    }else {
        return Promise.reject(error.response);
    }
});

export default function(url: string, method: 'GET' | 'get' | 'POST' | 'post' ='GET', submitData?: Record<string, any>) {
    return instance({
        url,
        method,
        [method.toLowerCase()==='get' ? 'params' : 'data']: submitData
    })
}